//import Tools from "./tools";

class Table {
    constructor(){
        this.init();
    }
    init(){
        //无异步操作
        this.initUrl();
        this.initOptionTemplate();
        this.bindSelector();
        //异步操作
        this.bindOperateEvents();
        this.initTableColumns();
        this.initTableOptions();
        this.table.bootstrapTable(this.options);
        this.bindTableClick();
    }
    bindTableClick(){
        this.table.on('dbl-click-row.bs.table', function (row, element, field) {
            if (element.fileType == 0) {
                var dirs = new Array();
                if (currentDir != "") {
                    dirs = currentDir.split('/');
                }
                dirs.push(element.name);
                currentDir = dirs.join('/');
                enterDir(currentDir);
            } else {
                console.info("当前不是目录");
            }
        });
    }
    initUrl(){
        this.fileContentUrl = "file/content";
        this.fileRenameUrl = "file/rename";
        this.fileCopyUrl = "file/copy";
        this.fileDeleteUrl = "file/delete";
        this.fileDownloadUrl = "files/download";
        this.fileListUrl = "file/list";
    }

    initOptionTemplate(){
        this.optionTemplate = `<div class="btn-group" role="group" aria-label="options">
            <button id="show" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span></button>
            <button id="edit" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></button>
            <button id="rename" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-retweet" aria-hidden="true"></span></button>
            <button id="copy" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-transfer" aria-hidden="true"></span></button>
            <button id="delete" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
            <button id="download" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-download-alt" aria-hidden="true"></span></button>
            </div>`;
    }

    initTableColumns(){
        this.tableColumns = [
            // {
            // checkbox : false, // 显示一个勾选框
            // align : 'center' // 居中显示
            // },
            {
                title: '编号', // 表格表头显示文字
                align: 'center', // 左右居中
                valign: 'middle', // 上下居中
                width: 20,
                // 返回序号，注意index是从0开始的，所以要加上1
                formatter: (value, row, index) => index + 1,
            },
            {
                field: 'name',
                title: '名称',
                align: 'center',
                valign: 'middle'
            },
            {
                field: 'fileType',
                title: '类型',
                align: 'center',
                valign: 'middle',
                formatter: (value, row, index)=> { // 单元格格式化函数
                    let text = '-';
                    if (value == 0) {
                        text = '<span class="glyphicon glyphicon-folder-open" aria-hidden="true"></span>'
                    } else if (value == 1) {
                        text = '<span class="glyphicon glyphicon-file" aria-hidden="true"></span>';
                    }
                    return text;
                }
            }, {
                field: 'authority',
                title: '权限',
                align: 'center',
                valign: 'middle',
            }, {
                title: "大小",
                field: 'length',
                align: 'center',
                valign: 'middle',
                formatter: (value, row, index)=> Tools.convertBytes(value)
            }, {
                title: "修改时间",
                field: 'lastModified',
                align: 'center',
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Tools.dateFormat(new Date(value), "yyyy-MM-dd hh:mm:ss");
                }
            }, {
                title: "操作",
                align: 'center',
                valign: 'middle',
                width: 220, // 定义列的宽度，单位为像素px
                formatter: (value, row, index) => this.optionTemplate,
                events: this.operateEvents,
            }];
    }


    initTableOptions(){
        this.options = { // 对应table标签的id
            method: "get",
            toolbar: "#toolbar",
            search: true,
            showRefresh: true,
            showToggle: true,
            showColumns: true,
            pagination: false, // 是否显示分页（*）
            sidePagination: "server", // 分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1, // 初始化加载第一页，默认第一页
            pageSize: 10, // 每页的记录行数（*）
            pageList: [10, 25, 50, 100], // 可供选择的每页的行数（*）
            sortable: false,
            url: this.fileListUrl, // 获取表格数据的url
            cache: false, // 设置为 false 禁用 AJAX 数据缓存， 默认为true
            striped: true, // 表格显示条纹，默认为false
            queryParams: { dir: currentDir },
            sortName: 'id', // 要排序的字段
            sortOrder: 'desc', // 排序规则
            columns: this.tableColumns,
            onLoadSuccess: (value) => console.info("加载成功"),
            onLoadError: (value) =>console.info("加载数据失败"),
        };
    }
    bindSelector(){
        this.table = $("#table");

        this.editModel = $("#edit-modal");
        this.editTitleId = $("#edit-title-id");
        this.editTextarea  = $("#edit-textarea");
        this.editSubmit = $("#edit-submit");

        this.fRenameInput = $("#f-rename-input");
        this.sRenameInput = $("#s-rename-input");
        this.renameModal = $("#rename-modal");

        this.fCopyInput = $("#f-copy-input");
        this.sCopyInput = $("#s-copy-input");
        this.copyModal = $("#copy-modal");

        this.body = $("body");
    }


    bindOperateEvents(){

        this.operateEvents = {

            "click #show": (e, value, row, index) => {
                console.log(Tools)
                let name = Tools.getCurrentName(row.name);
                console.log(name,"show")
                this.editModel.on("show.bs.modal", (e) => {
                    log("click",row.fileType);
                    if (row.fileType != 1) return false;
                    log("click",row.fileType);
                    $.post(this.fileContentUrl,
                        { name: name },
                        (value) => {
                        console.log(value.message)
                        this.editTitleId.text(row.name);
                        // TODO 此处应先将其格式化

                        this.editTextarea.text(value.message);
                        this.editTextarea.attr("readonly", "readonly");
                        this.editSubmit.hide();
                    });
                });
                console.log(this.editModel)
                this.editModel.modal('show');
            },
            "click #edit": (e, value, row, index) => {
                let name = Tools.getCurrentName(row.name);
                this.editModel.on("show.bs.modal", (e) => {
                    $.ajax({
                        type: "post",
                        url: this.fileContentUrl,
                        data: {
                            "name": name,
                            type: row.fileType
                        },
                        success: (value) => {
                            // console.log(value)
                            this.editTitleId.text(row.name);
                            this.editTextarea.removeAttr("readonly");
                            this.editTextarea.text(value.message);
                            this.editSubmit.show();
                        }
                    });
                });
                this.editModel.modal()
            },
            "click #rename": (e, value, row, index) => {

                var name = Tools.getCurrentName(row.name);
                this.fRenameInput.val(name);
                this.sRenameInput.val(name);
                this.renameModal.modal()
            },
            "click #copy": (e, value, row, index) => {
                var name = Tools.getCurrentName(row.name);
                var parentName = Tools.getParentName(name);
                log("parentName", parentName)
                this.fCopyInput.val(name);
                this.sCopyInput.val(parentName);
                this.copyModal.modal();
            },
            "click #delete": (e, value, row, index) => {
                var name = Tools.getCurrentName(row.name);
                $.get(this.fileDeleteUrl, {"name": name}, result =>{
                    enterDir(currentDir);
                });
            },
            "click #download": (e, value, row, index) => {
                //如果下载文件夹，直接返回（暂不支持）
                if (row.fileType != 1) return false;
                var name = Tools.getCurrentName(row.name);

//			    var tt =newDate().getTime();
                var url = this.fileDownloadUrl;
                var form = $("<form>");//定义一个form表单
                form.attr("style", "display:none");
                form.attr("target", "");
                form.attr("method", "get");//请求类型
                form.attr("action", url);//请求地址
                this.body.append(form);//将表单放置在web中

                var input = $("<input>");
                input.attr("type", "hidden");
                input.attr("name", "name");
                input.attr("value", name);
                form.append(input);
                form.submit();//表单提交
            },
        };
        console.log("bindOperateEvents",this.operateEvents)

    }

    
}